package com.demo.nfcdemo.v;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.demo.nfcdemo.DataTemp;
import com.demo.nfcdemo.R;
import com.demo.nfcdemo.adapter.NdefListAdapter;
import com.demo.nfcdemo.utils.NfcManger;
import com.demo.nfcdemo.utils.SP;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ljb
 * @des
 * @date 2020/5/23
 */
public class BActivity extends AppCompatActivity {
    private static final String TAG = "ReadSaveActivity";
    private static final int ACTION_WRITE = 1;
    private static final int ACTION_READ = 2;
    private static final int ACTION_SIMULATE = 5;

    private AlertDialog alertDialog;
    private NfcManger nfcManger;
    private int mAction;
    private NdefListAdapter ndefListAdapter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);
        nfcManger = new NfcManger(this);
        RecyclerView rv = findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(ndefListAdapter = new NdefListAdapter(this));

        //仿真卡模式
        ndefListAdapter.setOnItemClickListener((texts, position) -> {

            StringBuilder sb = new StringBuilder();
            for (String[] text : texts) {
                for (String s : text) {
                    sb.append(s);
                    sb.append("\n");
                }
            }
            showDialog("仿真卡模式...\n" + sb.toString());
            DataTemp.temp = sb.toString();
            mAction = ACTION_SIMULATE;
            closeNfc();
        });
        notifyRv();
    }

    @Override
    protected void onResume() {
        super.onResume();
        openNfc();
    }

    @Override
    protected void onPause() {
        super.onPause();
        closeNfc();
    }

    private void openNfc() {
        if (mAction != ACTION_SIMULATE) {
            //判断设备是否支持NFC功能
            if (nfcManger.isSupportNfc()) {
                //判断设备是否开启NFC功能
                if (nfcManger.isEnableNfc()) {
                    //注册FNC监听器
                    nfcManger.registerNfc(this);
                } else {
                    nfcManger.showNfcSetting(this);
                }
            } else {
                Toast.makeText(this, "当前设备不支持NFC功能", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void closeNfc() {
        nfcManger.unRegisterNfc(this);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            //写入数据到标签
            case R.id.bt_write:
                mAction = ACTION_WRITE;
                showDialog("等待写入标签数据...");
                openNfc();
                break;

            //读取标签数据
            case R.id.bt_read:
                mAction = ACTION_READ;
                showDialog("等待读取标签数据...");
                openNfc();
                break;
            case R.id.bt_clean:
                SP.put(this, "data", "");
                notifyRv();
            default:
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        switch (mAction) {
            case ACTION_WRITE:
                writeTest(intent);
                break;
            case ACTION_READ:
                readTest(intent);
                break;
            default:
        }
    }

    /**
     * 写入测试数据
     *
     * @param intent
     */
    private void writeTest(Intent intent) {
        //模拟数据
        boolean ret = nfcManger.writeNdef(intent, new String[]{"sssss", "ggggg"});
        if (ret) {
            showDialog("写入标签数据成功");
        } else {
            showDialog("写入标签数据失败");
        }
    }

    /**
     * 读取成功
     *
     * @param intent
     */
    private void readTest(Intent intent) {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
        String[][] texts = nfcManger.readNdef(intent);
        StringBuilder sb = new StringBuilder();
        for (String[] text : texts) {
            for (String s : text) {
                sb.append(s);
                sb.append("\n");
            }
        }
        new AlertDialog.Builder(this)
                .setMessage("读取标签内容为:\n" + sb.toString())
                .setPositiveButton("保存", (dialog, which) -> {
                    String data = (String) SP.get(this, "data", "");
                    List<String[][]> temp;
                    if (TextUtils.isEmpty(data)) {
                        temp = new ArrayList<>();
                    } else {
                        temp = new Gson().fromJson(data, new TypeToken<List<String[][]>>() {
                        }.getType());
                    }
                    temp.add(texts);
                    SP.put(this, "data", new Gson().toJson(temp));
                    Log.e(TAG, "readTest: " + new Gson().toJson(temp));

                    Toast.makeText(this, "已保存", Toast.LENGTH_SHORT).show();
                    notifyRv();
                }).setNegativeButton("取消", null)
                .show();
    }

    private void showDialog(String msg) {
        if (alertDialog == null) {
            alertDialog = new AlertDialog.Builder(this)
                    .create();
        }
        alertDialog.setMessage(msg);
        alertDialog.show();
    }

    private void notifyRv() {
        //回显数据
        String data = (String) SP.get(this, "data", "");
        List<String[][]> temp;
        if (TextUtils.isEmpty(data)) {
            temp = new ArrayList<>();
        } else {
            temp = new Gson().fromJson(data, new TypeToken<List<String[][]>>() {
            }.getType());
        }
        ndefListAdapter.setData(temp);
    }
}
